// addrspace.h
//	Data structures to keep track of executing user programs
//	(address spaces).
//
//	For now, we don't keep any information about address spaces.
//	The user level CPU state is saved and restored in the thread
//	executing the user program (see thread.h).
//
// Copyright (c) 1992-1993 The Regents of the University of California.
// All rights reserved.  See copyright.h for copyright notice and limitation
// of liability and disclaimer of warranty provisions.

#ifndef ADDRSPACE_H
#define ADDRSPACE_H

#include "copyright.h"
#include "filesys.h"
#include "bitmap.h"
#include "noff.h"

int allocateSharedMemory(int key, int numbytes, int flag);
void *attachSharedMemory(int key);
void detachSharedMemory(int addr, int key);
bool foundSharedMemKey(int key);

//Works when smaller too. This just give a bunch of room to grow.
#define UserStackSize 1024*1024         // increase this as necessary!

class AddrSpace {
public:
    AddrSpace(char* exe_filename);	// Create an address space,
                                        // initializing it with the program
                                        // stored in the file "exe_filename"
    //Make a copy of the address space (for fork).
    AddrSpace(const AddrSpace& source);
    ~AddrSpace();			// De-allocate an address space

    void InitRegisters();		// Initialize user-level CPU registers,
    // before jumping to user code

    void SaveState();			// Save/restore address space-specific
    void RestoreState();		// info on a context switch

    int stackArgs(int addr, char* name);

    char* read(int addr, int bytes);
    void write(int addr, char* str, int bytes);

    int allow_writes(int virt_page);
    int load_page(int virt_page);
    
    int readPage( int physicalPage, int virtualPage );
    int writePage( int physicalPage, int virtualPage );

    int addMoreSpace(int additionalPages);
    int attachShMem(int key, int start);
    void truncatePagesFrom(int page);
private:
    char* filename;
    NoffHeader noffH;
    BitMap* on_disk;
    TranslationEntry* pageTable;
    int numPages;	// Number of pages in the virtual address space
    int* page_sector;
    int victum_offset;
    int stack_base;
    int argc;
    int argv;
    bool forked;

    int store_page();
    int try_store_page();
};

#endif // ADDRSPACE_H
